<template>

    <div class="header">
        <div class="content">
            <div class="left">
                <el-button type="primary" size="large" round
                    @click="goTo('/home/file')"><el-icon><i-ep-MostlyCloudy /></el-icon>GLL云端</el-button>
                <el-button type="primary" size="large" round
                    @click="openExternalLink('http://10.223.15.55:3000/')"><el-icon><i-ep-ChatDotRound /></el-icon>GLL-AI聊天室</el-button>

            </div>
            <div class="right">

                <el-popover placement="bottom" title="测试章节" :width="400" trigger="click"
                    content="this is content, this is content, this is content">
                    <template #reference>
                        <el-badge :value="12" class="item" type="primary">
                            <el-button>一个测试按钮</el-button>
                        </el-badge>
                    </template>
                    <!-- 控制内容的按钮 -->
                    <div style="margin-top: 10px;">
                        <el-button @click="showPage(ShowDownload)">下载进度</el-button>
                        <el-button @click="showPage(ShowUpload)">上传进度</el-button>
                        <el-upload :show-file-list="false" :before-upload="handleBeforeUpload">
                            <el-button>测试上传</el-button>
                        </el-upload>
                    </div>
                    <!-- 动态组件加载区域 -->
                    <component :is="currentPageComponent" />

                </el-popover>


                <el-text class="r1" v-if="userInfo">{{ '欢迎，' + userInfo.username }}</el-text>
                <el-button circle @click="goTo('/user/info')">
                    <el-avatar :src="avatarUrl" large />
                </el-button>
            </div>
        </div>
    </div>

</template>

<script setup lang="ts">

import { useGoTo } from '@/hooks/useGoTo';
import axios from 'axios';
const { goTo } = useGoTo()
const store = useUserStore();
const userInfo = computed(() => store.user);
import { useUserStore } from '@/stores/userStore';

import { useUploadStore } from '@/stores/uploadStore';
// 获取上传状态存储 
const uploadStore = useUploadStore();


const avatarUrl = ref('');

// 定义状态变量来控制当前显示的页面组件
const currentPageComponent = shallowRef(ShowDownload);

// 定义显示页面的函数
const showPage = (page: any) => {
    currentPageComponent.value = page;
};

import ShowDownload from '@/views/Home/Show/ShowDownload.vue';
import ShowUpload from '@/views/Home/Show/ShowUpload.vue';


async function getImage() {
    try {
        // 假设你的后端API是/api/avatar，并且它接受一个参数userID  
        const response = await axios({
            method: 'get',
            url: `/api/user/getImage?email=${userInfo.value.email}`,
            responseType: 'blob', // 告诉axios我们期望一个blob响应  
        });

        // 创建一个指向blob的URL  
        avatarUrl.value = URL.createObjectURL(response.data);
    } catch (error) {
        console.error('获取头像失败:', error);
    }
}

function openExternalLink(externalUrl) {
    window.open(externalUrl, '_blank'); // 这将在新标签页中打开URL  
}


// 假设的基础上传URL
const baseUploadUrl = '/api/file/upload';

// 存储上传进度、文件信息、分块数量和当前分块序号
const uploadProgress = ref<number>(0);
const uploadingFile = ref<File | null>(null);
const chunkCount = ref<number>(0);
const currentChunkIndex = ref<number>(0);

// 计算带有用户ID的上传URL
const uploadUrlWithUserID = computed(() => {
    if (userInfo.value) {
        return `${baseUploadUrl}?userID=${userInfo.value.email}`;
    }
    return '';
});

// 处理文件上传前的逻辑
const handleBeforeUpload = (file: File) => {
    // 存储文件并初始化上传进度
    uploadingFile.value = file;
    uploadProgress.value = 0;

    // 初始化分块数量和当前分块序号
    initializeChunkedUpload(file);

    // 开始上传文件
    startChunkedUpload();

    // 阻止默认上传行为
    return false;
};

// 初始化分块上传的相关信息
const initializeChunkedUpload = (file: File) => {
    const chunkSize = 5 * 1024 * 1024; // 5MB per chunk
    chunkCount.value = Math.ceil(file.size / chunkSize);
    currentChunkIndex.value = 0;
};

// 分块上传文件
const startChunkedUpload = async () => {
    if (!uploadingFile.value) return;

    const chunkSize = 5 * 1024 * 1024; // 5MB per chunk
    const totalSize = uploadingFile.value.size;
    let uploadedSize = 0;
    // @ts-ignore
    const fileId = uploadStore.addFile(uploadingFile.value  );


    while (currentChunkIndex.value < chunkCount.value) {
        const start = currentChunkIndex.value * chunkSize;
        const end = Math.min(start + chunkSize, totalSize);
        const chunk = uploadingFile.value.slice(start, end);

        const formData = new FormData();
        formData.append('fileName', uploadingFile.value.name);
        formData.append('chunkNumber', currentChunkIndex.value.toString());
        formData.append('totalChunks', chunkCount.value.toString());

        //当前块的文件数据
        formData.append('chunk', chunk);
        //文件唯一id
        formData.append('fileId',fileId)

        formData.append('start', start.toString());
        formData.append('totalSize', totalSize.toString());

        console.log(formData.get('fileId'))
        try {
            const response = await axios.post(uploadUrlWithUserID.value, formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
                onUploadProgress: (progressEvent) => {
                    // 更新当前分块的上传进度
                    const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                    const chunkProgress = percentCompleted / 100;
                    const overallProgress = (currentChunkIndex.value / chunkCount.value) + (chunkProgress / chunkCount.value);
                    uploadProgress.value = Math.round(overallProgress * 100);
                },
            });

            if (response.status === 200 && response.data.code !== "-1") {
                // 假设服务器正确处理了分块上传
                uploadedSize += chunkSize;
                currentChunkIndex.value++;
            } else {
                ElMessage.error(response.data.msg);
                break;
            }
        } catch (error) {
            ElMessage.error('上传过程中发生错误');
            console.error(error);
            break;
        }
    }

    if (currentChunkIndex.value === chunkCount.value) {
        ElMessage.success('文件上传成功');
    }
};


onMounted(() => {
    if (userInfo.value) {
        getImage();
    }
})

watch(userInfo, (newVal, oldVal) => {
    if (newVal !== oldVal && newVal !== null) {
        // 当 userInfo 改变且不为 null 时调用 getImage 函数  
        getImage();
    }
}, { deep: true });



onUnmounted(() => {
    if (avatarUrl.value) {
        URL.revokeObjectURL(avatarUrl.value);
    }
})


</script>




<style scoped>
* {
    margin: 0;
    padding: 0;
}

.header {
    /* background-color: aqua; */
    position: fixed;
    z-index: 999;
    width: 100%;
    height: 70px;
    background: white;
    display: flex;
    justify-content: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content {
    width: 1200px;
    height: 70px;
    display: flex;
    justify-content: space-between;
}

.left {
    display: flex;
    align-items: center;
    justify-content: center;
}

.right {
    display: flex;
    align-items: center;
    justify-content: center;

}

.r1 {
    /* width: 200px; */
    padding-right: 20px;
    padding-left: auto;
}
</style>
